package controllers;

import java.nio.ByteBuffer;
import java.util.List;

import models.CategoryModel;
import models.ProductModel;
import play.Logger;
import play.cache.Cache;
import play.data.Upload;
import play.data.validation.Required;
import util.Contant;
import util.FsUtil;
import util.PaginationInfo;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;

public class Admin extends Login {
	
	private static void checkUserIsAdmin(){
		if(getUser() == null){
			Logger.info("user dont have is admin");
			renderTemplate(Contant.HOME_FO);
		}
	}
	
	//view list category in admin page
	public static void category(){
		checkUserIsAdmin();
		List<CategoryModel> categories = CategoryModel.listCategoies();
		render(categories);
	}
	
	//view list product in view/admin/product for admin page
	public static void product(int page){
		checkUserIsAdmin();
		List<ProductModel> totalProducts = ProductModel.listProducts();
		int total = totalProducts.size();
		Logger.info("total product size >> " + totalProducts.size());
		List<ProductModel> products = null;
		if(page == 0){
			page = 1;
		}
		products = ProductModel.getListProductLimit(totalProducts, page, Contant.PAGE_ITEM);	
		Logger.info("fetch Product >> " + products.size());
		PaginationInfo paginationInfo = FsUtil.pagingInAdmin(page, total, "Admin.product");
		List<CategoryModel> categories = CategoryModel.listCategoies();
		render(products, categories, paginationInfo);
	}
	
	//view list product in view/admin/product with status is active
	public static void activeProduct(int page){
		checkUserIsAdmin();
		List<ProductModel> totalProducts = ProductModel.listActiveProducts();
		int total = totalProducts.size();
		Logger.info("total product size >> " + totalProducts.size());
		List<ProductModel> products = null;
		if(page == 0){
			page = 1;
		}
		products = ProductModel.getListProductLimit(totalProducts, page, Contant.PAGE_ITEM);	
		PaginationInfo paginationInfo = FsUtil.pagingInAdmin(page, total, "Admin.activeProduct");
		List<CategoryModel> categories = CategoryModel.listCategoies();
		renderTemplate("Admin/product.html",products, categories, paginationInfo);
	}
	
	//view list product in view/admin/product with status is hidden
	public static void hiddenProduct(int page){
		checkUserIsAdmin();
		List<ProductModel> totalProducts = ProductModel.listHiddenProducts();
		int total = totalProducts.size();
		Logger.info("total product size >> " + totalProducts.size());
		List<ProductModel> products = null;
		if(page == 0){
			page = 1;
		}
		products = ProductModel.getListProductLimit(totalProducts, page, Contant.PAGE_ITEM);	
		PaginationInfo paginationInfo = FsUtil.pagingInAdmin(page, total, "Admin.hiddenProduct");
		List<CategoryModel> categories = CategoryModel.listCategoies();
		renderTemplate("Admin/product.html",products, categories, paginationInfo);
	}
	
	//create product in view/admin/product for Admin Page
	public static void createProduct(@Required Upload image, @Required String descShort, @Required String descDetail, @Required String name, @Required String category){
		checkUserIsAdmin();
		Logger.info("------------createProduct in admin page-------------------");
		//delete cache product
		FsUtil.deleteCacheProduct();
		FsUtil.deleteCacheProductFollowCategory(category);
		if (image == null) {
			Logger.info("--------not file------");
			String alias = FsUtil.convertUTF8TOASCII(name);
			ProductModel product = new ProductModel(name, "", descDetail,  alias,  descShort, "", false, category);
			product.insert();
			product(1);
		}
		if (validation.hasErrors()) {
			Logger.info("display error");
			flash.error("Oops, please input field required");
			product(1);
		}
		
		FileService fileService = FileServiceFactory.getFileService();
		AppEngineFile file;
		try {
			Logger.info("--------have file------");
			file = fileService.createNewBlobFile(image.getContentType(),
					image.getFileName());
			// Open a channel to write to it
			boolean lock = true;
			FileWriteChannel writeChannel = fileService.openWriteChannel(file,
					lock);
			writeChannel.write(ByteBuffer.wrap(image.asBytes()));
			writeChannel.closeFinally();
			BlobKey key = fileService.getBlobKey(file);
			
			String alias = FsUtil.convertUTF8TOASCII(name);
			ProductModel product = new ProductModel(name, key.getKeyString(), descDetail,  alias,  descShort, "", true, category);
			product.insert();
		} catch (Exception e) {
			Logger.info(e.getMessage());
		}
		product(1);
	}
	
	//delete Product in view/admin/product
	public static void deleteProduct(@Required long id){
		checkUserIsAdmin();
		ProductModel.deleteProduct(id);
		//delete cache product
		FsUtil.deleteCacheProduct();
		product(1);
	}
	
	//active product in view/admin/product
	public static void activeItemProduct(@Required long id){
		checkUserIsAdmin();
		ProductModel.activeItemProduct(id);
		//delete cache product
		FsUtil.deleteCacheProduct();
		activeProduct(1);
	}
	
	//active product in view/admin/product
	public static void hiddenItemProduct(@Required long id){
		checkUserIsAdmin();
		ProductModel.hiddenItemProduct(id);
		//delete cache product
		FsUtil.deleteCacheProduct();
		hiddenProduct(1);
	}
		
	//view edit Category in view/admin/viewEditProduct
	public static void viewEditProduct(@Required long id){
		checkUserIsAdmin();
		ProductModel product = ProductModel.getProductFollowId(id);
		List<CategoryModel> categories = CategoryModel.listCategoies();
		render(product, categories);
	}
	
	//submit edit product in Admin Page
	public static void editProduct(@Required Upload image, @Required String descShort, @Required String descDetail, @Required String name, @Required String category,  @Required long productId){
		checkUserIsAdmin();
		Logger.info("------------edit product in admin page-------------------");
		ProductModel productModel = ProductModel.getProductFollowId(productId);
		//delete cache product
		FsUtil.deleteCacheProduct();
		FsUtil.deleteCacheProductFollowCategory(category);
		if (image == null) {
			Logger.info("--------not file------");
			String alias = FsUtil.convertUTF8TOASCII(name);
			productModel.alias = alias;
			productModel.name = name;
			productModel.category = category;
			productModel.descDetail = descDetail;
			productModel.descShort = descShort;
			productModel.update();
			product(1);
		}
		if (validation.hasErrors()) {
			Logger.info("display error");
			flash.error("Oops, please input field required");
			product(1);
		}
		
		FileService fileService = FileServiceFactory.getFileService();
		AppEngineFile file;
		try {
			Logger.info("--------have file------");
			file = fileService.createNewBlobFile(image.getContentType(),
					image.getFileName());
			// Open a channel to write to it
			boolean lock = true;
			FileWriteChannel writeChannel = fileService.openWriteChannel(file,
					lock);
			writeChannel.write(ByteBuffer.wrap(image.asBytes()));
			writeChannel.closeFinally();
			BlobKey key = fileService.getBlobKey(file);
			//remove old image
			FsUtil.removeBlob(productModel.image);
			String alias = FsUtil.convertUTF8TOASCII(name);
			productModel.alias = alias;
			productModel.name = name;
			productModel.category = category;
			productModel.descDetail = descDetail;
			productModel.descShort = descShort;
			productModel.image =  key.getKeyString();
			productModel.update();
		} catch (Exception e) {
			Logger.info(e.getMessage());
		}
		product(1);
	}
		
	/********************************************************************************************************/
	//create category in view/admin/category for Admin Page
	public static void createCategory(@Required Upload data, @Required String description, @Required String name, @Required String selectbox){
		checkUserIsAdmin();
		Logger.info("--------selectbox------" + selectbox);
		if (data == null) {
			Logger.info("--------not file------");
			String alias = FsUtil.convertUTF8TOASCII(name);
			CategoryModel category = new CategoryModel(name, alias,
					description, "", selectbox);
			category.insert();
			category();
		}
		if (validation.hasErrors()) {
			Logger.info("display error");
			flash.error("Oops, please input field required");
			category();
		}
		if (selectbox.equals(util.Contant.DONG_PHUC)) {
			Cache.delete(util.Contant.DONG_PHUC);
		} else {
			Cache.delete(util.Contant.BHLD);
		}
		FileService fileService = FileServiceFactory.getFileService();
		AppEngineFile file;
		try {
			Logger.info("--------have file------");
			file = fileService.createNewBlobFile(data.getContentType(),
					data.getFileName());
			// Open a channel to write to it
			boolean lock = true;
			FileWriteChannel writeChannel = fileService.openWriteChannel(file,
					lock);
			writeChannel.write(ByteBuffer.wrap(data.asBytes()));
			writeChannel.closeFinally();
			BlobKey key = fileService.getBlobKey(file);
			String alias = FsUtil.convertUTF8TOASCII(name);
			CategoryModel category = new CategoryModel(name, alias,
					description, key.getKeyString(), selectbox);
			category.insert();
		} catch (Exception e) {
			Logger.info(e.getMessage());
		}
		category();
	}
	
	//delete Category in view/admin/category 
	public static void deleteCategory(@Required long id){
		checkUserIsAdmin();
		CategoryModel.deleteCategory(id);
		List<CategoryModel> categories = CategoryModel.listCategoies();
		renderTemplate("Admin/category.html", categories); 
	}
	
	//view edit Category in view/admin/viewEditcategory 
	public static void viewEditCategory(@Required long id){
		checkUserIsAdmin();
		CategoryModel category = CategoryModel.getCategoryFollowId(id);
		render(category);
	}
	
	//submit edit category in view/admin/category Admin Page
	public static void editCategory(@Required Upload data, @Required String description, @Required String name, @Required String selectbox,@Required long categoryId){
		Logger.info("--------edit category------");
		checkUserIsAdmin();
		CategoryModel categoryModel = CategoryModel.getCategoryFollowId(categoryId);
		if (data == null) {
			Logger.info("--------not file------");
			String alias = FsUtil.convertUTF8TOASCII(name);
			categoryModel.alias = alias;
			categoryModel.name = name;
			categoryModel.box = selectbox;
			categoryModel.description = description;
			categoryModel.update();
			category();
		}
		if (validation.hasErrors()) {
			Logger.info("display error");
			flash.error("Oops, please input field required");
			category();
		}
		if (selectbox.equals(util.Contant.DONG_PHUC)) {
			Cache.delete(util.Contant.DONG_PHUC);
		} else {
			Cache.delete(util.Contant.BHLD);
		}
		FileService fileService = FileServiceFactory.getFileService();
		AppEngineFile file;
		try {
			Logger.info("--------have file------");
			file = fileService.createNewBlobFile(data.getContentType(),
					data.getFileName());
			// Open a channel to write to it
			boolean lock = true;
			FileWriteChannel writeChannel = fileService.openWriteChannel(file,
					lock);
			writeChannel.write(ByteBuffer.wrap(data.asBytes()));
			writeChannel.closeFinally();
			BlobKey key = fileService.getBlobKey(file);
			//remove old image
			FsUtil.removeBlob(categoryModel.imagePath);
			String alias = FsUtil.convertUTF8TOASCII(name);
			categoryModel.alias = alias;
			categoryModel.name = name;
			categoryModel.imagePath = key.getKeyString();
			categoryModel.box = selectbox;
			categoryModel.description = description;
			categoryModel.update();
		} catch (Exception e) {
			Logger.info(e.getMessage());
		}
		category();
	}
	
}
